package com.yvan.demo.proj1;

import com.yvan.Conv;
import com.yvan.YvanUtil;
import com.yvan.http.HttpSession;
import com.yvan.http.YvanCookieJar;
import com.yvan.leto.ConfigChangeEvent;
import com.yvan.leto.ConfigListener;
import com.yvan.leto.LetoManage;
import com.yvan.leto.SegmentHelper;
import com.yvan.leto.listener.LogbackListener;
import com.yvan.platform.JsonWapper;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.ByteArrayInputStream;
import java.util.Properties;

@Slf4j
public class StartProj1 {

    private static final JsonWapper jsonWapperDatax = new JsonWapper();

    @SneakyThrows
    public static void main(String[] args) {
        log.info(YvanUtil.toJsonPretty(LetoManage.appConfig));

        LetoManage.addListener(new LogbackListener());
        LetoManage.addListener(new dataxConfig());
        LetoManage.addListener(new gameConfig());
        LetoManage.init();


        log.info("init finished");

        log.info("logback content:" + Conv.NS(LetoManage.getSegmentContent(SegmentHelper.LOGBACK)).replace("\n", ""));
        log.info("jw content:" + LetoManage.getJsonWapper(SegmentHelper.SPRING_BOOT).toString(false));

        log.info("baidu");
        HttpSession httpSession = new HttpSession(new YvanCookieJar());
        String body = httpSession.curl().get("http://www.baidu.com").execute().body().string();
        log.info("got " + body.length() + " bytes");

        Thread.sleep(Integer.MAX_VALUE);
    }

    static class gameConfig implements ConfigListener {
        @Override
        public String watchSegment() {
            return "game";
        }

        @Override
        @SneakyThrows
        public void onChange(ConfigChangeEvent changeEvent) {
            val prop = new Properties();
            @Cleanup val inputStream = new ByteArrayInputStream(changeEvent.getChanges().getBytes("utf-8"));
            prop.load(inputStream);
            log.info(prop.toString());
        }
    }

    static class dataxConfig implements ConfigListener {

        @Override
        public String watchSegment() {
            return "datax";
        }

        @Override
        public void onChange(ConfigChangeEvent changeEvent) {
            jsonWapperDatax.resetInnerMap(YvanUtil.readYaml(changeEvent.getChanges()));
            log.info(jsonWapperDatax.toString(false));
        }
    }
}
